//Given the head of a linked list, remove the nᵗʰ node from the end of the list 
//and return its head. 
//
// 
// Example 1: 
//
// 
//Input: head = [1,2,3,4,5], n = 2
//Output: [1,2,3,5]
// 
//
// Example 2: 
//
// 
//Input: head = [1], n = 1
//Output: []
// 
//
// Example 3: 
//
// 
//Input: head = [1,2], n = 1
//Output: [1]
// 
//
// 
// Constraints: 
//
// 
// The number of nodes in the list is sz. 
// 1 <= sz <= 30 
// 0 <= Node.val <= 100 
// 1 <= n <= sz 
// 
//
// 
// Follow up: Could you do this in one pass? 
// Related Topics Linked List Two Pointers 👍 7620 👎 382

  
package leetcode.editor.en;

import listnode.ListNode;

public class _19_RemoveNthNodeFromEndOfList{
    public static void main(String[] args) {
         Solution solution = new _19_RemoveNthNodeFromEndOfList().new Solution();
    }
    //leetcode submit region begin(Prohibit modification and deletion)
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode removeNthFromEnd1(ListNode head, int n) {
        ListNode first = head;
        ListNode last = head;
        for (int i = 0; i < n; i++) {
            last = last.next;
        }
        if (last == null) {
            return first.next;
        }
        while (last.next!=null) {
            first = first.next;
            last = last.next;
        }
        first.next = first.next.next;
        return head;
    }

    public ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode first = head;
        ListNode last = head;
        for (int i = 0; i < n; i++) {
            last = last.next;
        }
        if (last==null) {
            return first.next;
        }
        while (last.next != null) {
            first = first.next;
            last = last.next;
        }
        first.next = first.next.next;
        return head;

    }
}
//leetcode submit region end(Prohibit modification and deletion)

}